/**
 * 
 */
package u.can.i.up.db.mongo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

import u.can.i.up.utils.JsonUtils;

/**
 * 
 * @author tinyyard
 *
 */
public class AppAntivirusResultService {

	private static final Logger LOGGER = LogManager.getLogger();
	private static DBCollection results = null;

	private static MongodbService mongodbService = new MongodbService();

	public AppAntivirusResultService() {
		results = MongodbConnFactory.getCollection("app.antivirus.result");
	}

	/**
	 * save android antivirus analysis result to mongodb
	 * 
	 * @param androidDynamicResult
	 */
	// public void insert(AppAntivirusResult appAntivirusResult) {
	// JsonConfig jsonConfig = JsonUtils
	// .getJsonConfigForThrift("com.softsec.tase.common.rpc.domain.app.AppAntivirusResult");
	// mongodbService.insertItem(results,
	// MongodbUtils.beanToDBObj(appAntivirusResult, jsonConfig));
	// LOGGER.info("Received virus total result : " +
	// appAntivirusResult.getMd5());
	// }

	/**
	 * get App antivirus result by checksum
	 * 
	 * @param fileMD5
	 * @return AppAntivirusResult
	 */
	@SuppressWarnings("unchecked")
	public AppAntivirusResult getAppAntivirusResultByChecksum(String fileMD5) {
		AppAntivirusResult appAntivirusResult = new AppAntivirusResult();
		try {
			DBObject dbObject = new BasicDBObject("md5", fileMD5);
			// appAntivirusResult=getSingleAppAntivirusResults(dbObject);
			DBObject resultDbObject = mongodbService.getSingleItem(results, dbObject);
			appAntivirusResult.setMd5(fileMD5);
			appAntivirusResult.setDetect_md5(resultDbObject.get("md5").toString());
			appAntivirusResult.setPermalink(resultDbObject.get("permalink").toString());
			appAntivirusResult.setPositives((String) resultDbObject.get("positives"));
			appAntivirusResult.setResource(resultDbObject.get("resource").toString());
			appAntivirusResult.setResponse_code(resultDbObject.get("response_code").toString());
			appAntivirusResult.setScan_date(resultDbObject.get("scan_date").toString());
			appAntivirusResult.setScan_id(resultDbObject.get("scan_id").toString());
			appAntivirusResult.setScans((List<AppAntivirusScans>) resultDbObject.get("scans"));
			appAntivirusResult.setSha1(resultDbObject.get("sha1").toString());
			appAntivirusResult.setSha256(resultDbObject.get("sha256").toString());
			appAntivirusResult.setTotal(resultDbObject.get("total").toString());
			appAntivirusResult.setVerbose_msg(resultDbObject.get("verbose_msg").toString());
		} catch (Exception e) {
			LOGGER.error("Fail to get android virus result by file checksum [" + fileMD5 + "]");
			e.printStackTrace();
		}
		return appAntivirusResult;
	}

	/**
	 * 
	 * @param query
	 * @return
	 */
	@SuppressWarnings("unused")
	private AppAntivirusResult getSingleAppAntivirusResults(DBObject query) {
		DBObject dbObj = mongodbService.getSingleItem(results, query);
		if (dbObj == null) {
			return null;
		} else {
			Map<String, Object> classMap = new HashMap<String, Object>();
			classMap.put("response_code", String.class);
			classMap.put("verbose_msg", String.class);
			classMap.put("resource", String.class);
			classMap.put("scan_id", String.class);
			classMap.put("md5", String.class);
			classMap.put("detect_md5", String.class);
			classMap.put("sha1", String.class);
			classMap.put("sha256", String.class);
			classMap.put("scan_date", String.class);
			classMap.put("positives", String.class);
			classMap.put("total", String.class);
			classMap.put("scans", AppAntivirusScans.class);
			classMap.put("permalink", String.class);
			classMap.put("reportPath", String.class);
			return (AppAntivirusResult) (JsonUtils.deserialize(JSON.serialize(dbObj), AppAntivirusResult.class,
					classMap));
		}
	}

	/**
	 * remove Single Virus Result by checksum
	 * 
	 * @param fileChecksum
	 */
	public void removeSingleVirusResult(String fileChecksum) {
		DBObject delete = new BasicDBObject("md5", fileChecksum);
		if (getAppAntivirusResultByChecksum(fileChecksum) != null) {
			mongodbService.deleteSingleItem(results, delete);
			LOGGER.info("delete android antivirus result,Md5:" + fileChecksum);
		}
	}

	@SuppressWarnings("unchecked")
	public List<AppAntivirusResult> getAppAntivirusResultsByPositives(int mPositives) {
		List<AppAntivirusResult> appAntivirusResults = new ArrayList<AppAntivirusResult>();
		DBCursor dbCursor = results.find();// .limit(10000);
		while (dbCursor.hasNext()) {
			DBObject resultDbObject = dbCursor.next();
			int cPositives = Integer.valueOf((String) resultDbObject.get("positives"));
			if (cPositives >= mPositives) {
				String md5 = (String) resultDbObject.get("md5");

				AppAntivirusResult appAntivirusResult = new AppAntivirusResult();
				appAntivirusResult.setMd5(md5);
				appAntivirusResult.setDetect_md5(resultDbObject.get("md5").toString());
				appAntivirusResult.setPermalink(resultDbObject.get("permalink").toString());
				appAntivirusResult.setPositives((String) resultDbObject.get("positives"));
				appAntivirusResult.setResource(resultDbObject.get("resource").toString());
				appAntivirusResult.setResponse_code(resultDbObject.get("response_code").toString());
				appAntivirusResult.setScan_date(resultDbObject.get("scan_date").toString());
				appAntivirusResult.setScan_id(resultDbObject.get("scan_id").toString());
				appAntivirusResult.setScans((List<AppAntivirusScans>) resultDbObject.get("scans"));
				appAntivirusResult.setSha1(resultDbObject.get("sha1").toString());
				appAntivirusResult.setSha256(resultDbObject.get("sha256").toString());
				appAntivirusResult.setTotal(resultDbObject.get("total").toString());
				appAntivirusResult.setVerbose_msg(resultDbObject.get("verbose_msg").toString());
				appAntivirusResults.add(appAntivirusResult);
			}
		}
		return appAntivirusResults;
	}

}
